package com.jifeng.br.pjj.bookreader.controller.admin;

import com.jifeng.br.pjj.bookreader.service.CodeService;
import com.jifeng.br.pjj.bookreader.service.TokenService;
import com.jifeng.br.pjj.bookreader.service.UserinfoService;
import com.jifeng.br.pjj.bookreader.util.R;
import com.jifeng.br.pjj.bookreader.util.form.LoginForm;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author PangJunjie
 * @Date 2023/7/11/011
 */
@RestController
public class LoginController extends BaseController {
    @Autowired
    private UserinfoService userinfoService;

    @Autowired
    private CodeService codeService;
    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public R login(@RequestBody LoginForm loginForm) {
        return userinfoService.login(loginForm);
    }

    @GetMapping("/logout")
    public R logout() {
        tokenService.saveToken(getUserId());
        return R.ok();
    }


    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response, String uuid) throws IOException {
        /*设置输出头*/
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        /*根据验证码生成图片*/
        BufferedImage bi = codeService.getKaptcha(uuid);
        /*获取输出流*/
        ServletOutputStream out = response.getOutputStream();
        /*输出图片*/
        ImageIO.write(bi, "jpg", out);
//        out.close();
        /*关闭输出流*/
        IOUtils.closeQuietly(out);
    }
}
